package com.emotion.recognition.shared;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public enum Emotion {
    ASTONISHED("0001"), CALM("0010"), SAD("0100"), SMILING("1000"), NONE("0000");

    private final String oneHot;

    Emotion(String oneHot) {
        this.oneHot = oneHot;
    }

    public List<Double> getOneHotEncoded() {
        List<Double> doubles = new ArrayList<Double>();
        for (char c : oneHot.toCharArray()) {
            if (c == '1') {
                doubles.add(1.0d);
            } else {
                doubles.add(0.0d);
            }
        }
        return Collections.unmodifiableList(doubles);
    }

    public static Emotion fromOrdinal(int ord) {
        switch (ord) {
            case 0:
                return ASTONISHED;
            case 1:
                return CALM;
            case 2:
                return SAD;
            case 3:
                return SMILING;
            default:
                throw new UnsupportedOperationException();
        }
    }

    public static Emotion parseOneHotEncoded(List<Double> oneHot) {
        // Support for arrays that have a range of values. Take max index and
        // set it to 1. Rest to 0. If there is a tie, take the last one.
        StringBuilder str = new StringBuilder("0000");
        double max = Double.NEGATIVE_INFINITY;
        int index = 0;
        for (int i = 0; i < oneHot.size(); ++i) {
            if (oneHot.get(i) > max) {
                max = oneHot.get(i);
                index = i;
            }
        }
        str.setCharAt(index, '1');

        // Find a match
        for (Emotion e : values()) {
            if (str.toString().equals(e.oneHot)) {
                return e;
            }
        }
        return NONE;
    }

    /**
     * Same as Emotion.valueOf But allows for none.
     * 
     * @param emotion
     * @return
     */
    public static Emotion getEmotionByString(String emotion) {
        if (emotion.equals("SMILING")) {
            return Emotion.SMILING;
        } else if (emotion.equals("SAD")) {
            return Emotion.SAD;
        } else if (emotion.equals("ASTONISHED")) {
            return Emotion.ASTONISHED;
        } else if (emotion.equals("CALM")) {
            return Emotion.CALM;
        } else {
            return Emotion.NONE;
        }
    }
}